package com.tidc.seaserverservice.util;

import com.tidc.seaservermapper.dao.UserDao;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：冯涛滔
 * @date ：Created in 2020/9/11 15:19
 * @description：
 * @modified By：
 * @version:
 */
@Component
public class TokenUtil {

    @Resource
    private UserDao userDao;
    public String createToken(UserDetails userDetails){
        Date accessTimeData = new Date(System.currentTimeMillis() + 2 * 60 * 60 * 1000);
//        Date refreshTimeData = new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000);
        Map<String,Object> map = new HashMap<>();
        map.put("userInfo",userDetails.getUsername());
        map.put("authorities", userDetails.getAuthorities());
        String accessToken = Jwts.builder()
                .addClaims(map)
                .setSubject(userDetails.getUsername())
                .setExpiration(accessTimeData)
                .signWith(SignatureAlgorithm.HS512, "tidc")
                .compact();
        return accessToken;
    }
    /**
     * 解析token
     * @param token
     * @return
     */
    private static Claims getTokenBody(String token){
        return Jwts.parser()
                //.setSigningKey(publicKey)
                .setSigningKey("tidc")
                .parseClaimsJws(token)
                .getBody();
    }
    /**
     * 解析token,获得subject中的信息
     * @param token
     * @return
     */
    public static String parseToken(String token) {
        String subject = null;
        try {
            subject = getTokenBody(token).getSubject();
        } catch (Exception e) {
        }
        return subject;
    }

    /**
     * 获取token自定义属性
     * @param token
     * @return
     */
    public static Map<String,Object> getClaims(String token){
        Map<String,Object> claims = null;
        try {
            claims = getTokenBody(token);
        }catch (Exception e) {
        }

        return claims;
    }

}
